import { useState } from "react"
import SyntaxHighlighter from '@/components/SyntaxHighlighter'


const throttleFn = (fn, wait) => {
  let timer = null

  return function(...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, wait)
    }
  }
}

const consoleFn = throttleFn(() => {
  console.log('我是通过封装函数 throttleFn 实现的节流')
}, 1000)

const code1 = `
  let timer = null

  function Throttle() {
    const [count, setCount] = useState(0)

    const handleAdd = () => {
    if (!timer) {
      timer = setTimeout(() => {
        setCount(count + 1)
        timer = null
      }, 1000)
    }
    }

    return (
      <div>
        <p>手写一个节流函数</p>
        <p>当前数字的值：{ count }</p>
        <button onClick={handleAdd}>Add</button>
      </div>
    )
  }



  // 封装成方法
  const throttleFn = (fn, wait) => {
    let timer = null

    return function(...args) {
      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(this, args)
          timer = null
        }, wait)
      }
    }
  }

  const consoleFn = throttleFn(() => {
    console.log('我是通过封装函数 throttleFn 实现的节流')
  }, 1000)
`

let timer = null

function Throttle() {
  const [count, setCount] = useState(0)

  const handleAdd = () => {
   if (!timer) {
    timer = setTimeout(() => {
      setCount(count + 1)
      timer = null
    }, 1000)
   }
  }

  const handleConsole = () => {
    consoleFn()
  }

  return (
    <div>
      <p>手写一个节流函数</p>
      <p>当前数字的值：{ count }</p>
      <button onClick={handleAdd}>Add</button>

      <p>控制台里可查看封装的函数</p>
      <button onClick={handleConsole}>控制台里查看打印效果</button>

      <p>代码实现逻辑：</p>
      <SyntaxHighlighter children={code1} />
    </div>
  )
}

export default Throttle